package com.siyoumi.app.sys.wx;

import com.siyoumi.app.sys.service.wx_center.CenterHandler;
import com.siyoumi.app.sys.service.wx_center.CenterHandlerData;
import com.siyoumi.app.sys.wx.thread.WxCenterThread;
import com.siyoumi.app.sys.wx.thread.WxCenterThreadLocal;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.controller.ApiController;
import com.siyoumi.entity.SysAccsuperConfig;
import com.siyoumi.service.SysAccsuperConfigService;
import com.siyoumi.util.XHttpClient;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

//公众号回复
@Slf4j
@RestController
@RequestMapping({"/wx/center", "/wx_open/server/callback/{appid}"})
public class WxCenter
        extends ApiController {
    //授权
    @RequestMapping("")
    public Object index(@RequestBody(required = false) String inXmlMsg, @PathVariable(required = false) String appid) {
        log.info("xml：{}", inXmlMsg);
        log.info("appid: {}", appid);

        WxCenterThreadLocal.remove();

        String x = null;
        if (XStr.hasAnyText(appid)) {
            log.debug("授权站点");
            SysAccsuperConfig entityConfig = SysAccsuperConfigService.getBean().getXConfigByAppId(appid);
            if (entityConfig != null) {
                x = entityConfig.getKey();
            }
        }
        if (XStr.isNullOrEmpty(x)) {
            x = XHttpContext.getX();
        }

        if (XStr.isNullOrEmpty(x)) {
            XValidator.err(50136, "miss x");
        }

        String echostr = CenterHandler.getInstance(x).checkSign();
        if (echostr != null) {
            getResponse().setContentType("text/plain");
            return echostr;
        }

        if (XStr.isNullOrEmpty(inXmlMsg)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        InputData inputData = InputData.fromRequest();
        String run = inputData.input("run");

        if ("1".equals(run)) {
            CenterHandler handler = CenterHandler.getInstance(x);
            CenterHandlerData data = CenterHandlerData.getInstance(inXmlMsg, x);
            handler.handle(data);
        } else {
            String url = XHttpContext.getUrlPathAndQuery() + "&run=1";
            String port = "8010";
            String root = "http://127.0.0.1:" + port;

            String urlTrue = root + url;

            WxCenterThreadLocal.setUrl(url);
            WxCenterThreadLocal.setXml(inXmlMsg);

            Thread thread = new Thread(() -> {
                postXml(urlTrue, inXmlMsg);
            });
            log.debug("thread_id：{}", thread.getId());

            WxCenterThread wxCenterThread = XSpringContext.getBean(WxCenterThread.class);
            wxCenterThread.getPool().submit(thread);
            //thread.start();
        }

        WxCenterThreadLocal.remove();
        return ResponseEntity.ok().build();
    }


    static public void postXml(String url, String xml) {
        XHttpClient client = XHttpClient.getInstance(3000);
        client.postBody(url, null, xml);
    }
}
